<template>
  <div class="pre-view">
    <div class="file-preview">
      <VueOfficeDocx v-if="oFileType === 'docx'" style="height: 100%;" :src="oSrc" />
      <VueOfficeExcel v-if="oFileType === 'xls' || oFileType === 'xlsx'" style="height: 500px;" :src="oSrc" />
      <VueOfficePdf v-if="oFileType === 'pdf'"  :src="oSrc" />
      <img v-if="oFileType === 'png' || oFileType === 'jpg' || oFileType === 'jpeg'" style="width: 100%;" :src="oSrc" alt="" />
    </div>
  </div>
</template>

<script setup>
import {ref, watch} from 'vue'
import {svc} from '@/config/common'

// docx预览插件
import VueOfficeDocx from '@vue-office/docx'
import '@vue-office/docx/lib/index.css'
import '@vue-office/docx/lib/index.css'
// excel预览插件
import VueOfficeExcel from '@vue-office/excel'
import '@vue-office/excel/lib/index.css'
// pdf预览插件
import VueOfficePdf from '@vue-office/pdf'

import axios from 'axios'
import {doGet} from "@/config/http";

const props = defineProps({
  attachmentId: {
    required: true,
    type: String,
    default: '',
  },
})

const emit = defineEmits();

let oFileType = ref('')
let oSrc = ref(null)

watch(() => props.attachmentId, val => {
  console.debug('val----------------',val)
  if (val) {
    oSrc.value = null
    doGet(svc, `/attachment/${val}`, {}, false).then(res => {
      let fileName = res.original.split('.');
      oFileType.value = fileName[fileName.length - 1]
      getFile(res.id).then(res => {
        oSrc.value = window.URL.createObjectURL(new Blob([res]))
      });
    })
  }
});

function getFile(id) {
  return new Promise((resolve, reject) => {
    axios({
      method:'get',
      url: '/' + svc + '/api/v1/customAttachment/download/' + id,
      responseType:'arraybuffer'
    }).then(data => {
      resolve(data.data)
    }).catch(error => {
      reject(error.toString())
    })
  })
}
</script>
<style scoped>
.pre-view {
  width: 100%;
  max-height: 100vh;
  /* height: 100%; */
  /* padding: 15px; */
  box-sizing: border-box;
}
.select-file {
  width: 100%;
  height: 35px;
  border-bottom: 1px dashed #ccc;
  margin-bottom: 15px;
}
.file-preview {
  width: 100%;
  max-height: 100vh;
  /* height: 500px; */
  border: 1px dashed #007acc;
  overflow-x: auto;
  overflow-y: auto;
  text-align: center;
}
</style>
